package com.ideaplugin.datamanager.config;

import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Component
public class DataSourceConfig {


    @Primary
    @Bean
    @ConditionalOnProperty(name = "spring.datasource.multi.enable", havingValue = "true")
    public DataSource dynamicDataSource() {
        final MultiDataSourceProperties sourceProperties = SpringUtil.getBean(MultiDataSourceProperties.class);
        final DataSource mainDataSource = SpringUtil.getBean(DataSourceProperties.class).initializeDataSourceBuilder().build();
        final DataSourceProperties[] extensionDataSources = sourceProperties.getExtensionDataSources();
        Map<Object, Object> targetDataSources = new HashMap<>();
        if (extensionDataSources != null && extensionDataSources.length > 0) {
            for (int i = 0; i < extensionDataSources.length; i++) {
                final DataSourceProperties dataSourceProperties = extensionDataSources[i];
                final DataSource slaveDataSource = dataSourceProperties.initializeDataSourceBuilder().build();
                String dataDsName = "slave" + i;
                if (StrUtil.isNotBlank(dataSourceProperties.getName())) {
                    dataDsName = dataSourceProperties.getName();
                }
                targetDataSources.put(dataDsName, slaveDataSource);
            }
        }
        return new DynamicDataSource(mainDataSource, targetDataSources);
    }


}
